package com.hkts.naturalgas.performance.service.serviceimpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkts.naturalgas.constant.PerformanceConstant;
import com.hkts.naturalgas.flow.service.IFlowTaskInstanceService;
import com.hkts.naturalgas.performance.entity.*;
import com.hkts.naturalgas.performance.mapper.*;
import com.hkts.naturalgas.performance.performanceVo.*;
import com.hkts.naturalgas.performance.service.IHkAssessmentInfoService;
import com.hkts.naturalgas.performance.service.IHkFormEntityService;
import com.hkts.naturalgas.utils.BeanConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yck
 * @since 2020-12-22
 */
@Service
@Transactional
public class HkFormEntityServiceImpl extends ServiceImpl<HkFormEntityMapper, HkFormEntity> implements IHkFormEntityService {


    @Autowired
    private HkFormEntityMapper hkFormEntityMapper;
    @Autowired
    private HkFormRelationShipMapper hkFormRelationShipMapper;
    @Autowired
    private HkFormIndexMapper hkFormIndexMapper;

    @Autowired
    private HkAssessmentPictureMapper hkAssessmentPictureMapper;

    @Autowired
    private HkAssessmentScoreMapper hkAssessmentScoreMapper;
    @Autowired
    private HkAssessmentInfoMapper hkAssessmentInfoMapper;

    @Autowired
    private IFlowTaskInstanceService flowTaskInstanceService;

    @Override
    public IPage<HkFormEntity> selectPage(Page<HkFormEntity> page, HkFormEntity hkFormEntity) {
        QueryWrapper<HkFormEntity> query = Wrappers.query();
        QueryWrapper<HkFormEntity> entityWrapper = getEntityWrapper(query, hkFormEntity);
        return hkFormEntityMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<HkFormEntity> selectList(HkFormEntity hkFormEntity) {
        QueryWrapper<HkFormEntity> query = Wrappers.query();
        QueryWrapper<HkFormEntity> entityWrapper = getEntityWrapper(query, hkFormEntity);
        return hkFormEntityMapper.selectList(entityWrapper);
    }

    @Override
    public List<FormAndItemResultVo> getFormEntityByProessId(String proessId) {
        /*
         * 根据流程实例id获取所有当前得分
         * */
        QueryWrapper<HkAssessmentScore> query = Wrappers.query();
        query.eq(HkAssessmentScore.PROCESS_INSTANCE_ID, proessId);
        query.eq(HkAssessmentScore.IS_CURRENT_ASSESSMENT, "1");
        List<HkAssessmentScore> hkAssessmentScores = hkAssessmentScoreMapper.selectList(query);
        String hontUserId = hkAssessmentScores.get(0).getHontUserId();
        HkFormEntity hkFormEntity = hkFormEntityMapper.selectFormEntityByUserId(hontUserId);
        QueryWrapper<HkFormRelationShip> query1 = Wrappers.query();
        QueryWrapper<HkFormRelationShip> eq = query1.eq(HkFormRelationShip.FORM_ID, hkFormEntity.getId());
        eq.orderByAsc(HkFormRelationShip.SORT_NUMBER);
        List<HkFormRelationShip> hkFormRelationShips = hkFormRelationShipMapper.selectList(eq);
        List<String> items = new ArrayList<String>();
        Map<String, String> realtionMap = new HashMap<>();
        for (int i = 0; i < hkFormRelationShips.size(); i++) {
            HkFormRelationShip hkFormRelationShip = hkFormRelationShips.get(i);
            items.add(hkFormRelationShip.getItemId());
            realtionMap.put(hkFormRelationShip.getItemId(), hkFormRelationShip.getFormId());
        }
        List<FormAndItemResultVo> resultVo = new ArrayList<FormAndItemResultVo>();
        List<FormAndItemResultVo> scoreVo = new ArrayList<FormAndItemResultVo>();
        List<FormAndItemResultVo> deleteVo = new ArrayList<FormAndItemResultVo>();
        List<FormAndItemResultVo> addVo = new ArrayList<FormAndItemResultVo>();
        /*
         * 将表单分项和加分项进行重新排序并按加减分分组
         * 将该表单所有表单项关联查询
         *
         * */

        /*
         * 记录是否包含自定义加减选项
         * */
        List<String> scoreIds = new ArrayList<String>();
        hkAssessmentScores.stream().forEach(hkAssessmentScore -> {
            FormAndItemResultVo vo = new FormAndItemResultVo();
            scoreIds.add(hkAssessmentScore.getIndexId());
            vo.setIndexName(hkAssessmentScore.getIndexName());
            vo.setFormIndexId(realtionMap.get(hkAssessmentScore.getIndexId()));
            vo.setScore(hkAssessmentScore.getScore());
            /*vo.setNumId(hkAssessmentScore.getNumId());
            vo.setTxtId(hkAssessmentScore.getTxtId());*/
            vo.setIndexDescribe(hkAssessmentScore.getIndexDescribe());
            vo.setProcessInstanceId(hkAssessmentScore.getProcessInstanceId());
            vo.setIndexId(hkAssessmentScore.getIndexId());
            //TODO 给vo添加图片
            List<String> igms=selectImgs(hkAssessmentScore);
            vo.setImglist(igms);
            /*
             * 根据考核指标查找表单项
             * */
            if(hkAssessmentScore.getIndexComment()!=null){
                vo.setIndexComment(hkAssessmentScore.getIndexComment());
            }else{
                //当前的评论为空，查找之前的评论

            }
            if (vo.getIndexId().equals(PerformanceConstant.IS_CUSTOM_ADD)  ) {
                int i = hkAssessmentScore.getScore().intValue();
                vo.setIndexFrequency(hkAssessmentScore.getIndexFrequency());
                //查询自定义加的表单项
                QueryWrapper<HkFormIndex> queryDelete = Wrappers.query();
                queryDelete.eq("is_custome_add","1");
                List<HkFormIndex> hkFormIndices = hkFormIndexMapper.selectList(queryDelete);
//                vo.setFormIndexJson(hkFormIndices.get(0).getFormIndexJson());
                vo.setIndexScore((float)1);
            }else if(vo.getIndexId().equals(PerformanceConstant.IS_CUSTOM_DELETE)){
                int i = hkAssessmentScore.getScore().intValue();
                vo.setIndexFrequency(hkAssessmentScore.getIndexFrequency());
                //查询自定义减的表单项
                QueryWrapper<HkFormIndex> queryDelete = Wrappers.query();
                queryDelete.eq("is_custome_delete","1");
                List<HkFormIndex> hkFormIndices = hkFormIndexMapper.selectList(queryDelete);
//                vo.setFormIndexJson(hkFormIndices.get(0).getFormIndexJson());
                vo.setIndexScore((float)-1);
            } else {
                QueryWrapper<HkFormIndex> query2 = Wrappers.query();
                query2.eq("assessment_index_id",hkAssessmentScore.getIndexId());
                List<HkFormIndex> hkFormIndices = hkFormIndexMapper.selectList(query2);
//                vo.setFormIndexJson(hkFormIndices.get(0).getFormIndexJson());
                vo.setIndexFrequency(hkAssessmentScore.getIndexFrequency());
            }
                scoreVo.add(vo);

        });
        /*
         * 将表单所有表单项查询出并排序
         * */
        FormItemSortVo vo1=new FormItemSortVo();
        vo1.setFormId(hkFormEntity.getId());
        vo1.setList(items);
        List<FormAndItemResultVo> formAndItemResultVos = hkFormRelationShipMapper.selectFormAndItemResultVoByFormItemIds(vo1);
        for (int i = 0; i < formAndItemResultVos.size(); i++) {
            if (scoreIds.contains(formAndItemResultVos.get(i).getIndexId())) {
                 /*
                 yck 2021 当为打分项时将indexScore 装入之前的model中
                 * 当
                 * */
                for(int j=0;j<scoreVo.size();j++){
                    if(formAndItemResultVos.get(i).getIndexId().equals(scoreVo.get(j).getIndexId())){
                        scoreVo.get(j).setIndexScore(formAndItemResultVos.get(i).getIndexScore());
                    }
                }
                continue;
            }
            if (formAndItemResultVos.get(i).getIndexScore() > 0) {
                addVo.add(formAndItemResultVos.get(i));
            } else {
                deleteVo.add(formAndItemResultVos.get(i));
            }
        }
        /*
         * 判断是否有自定义加
         * */

        if (!scoreIds.contains(PerformanceConstant.IS_CUSTOM_ADD)) {
            Map addMap = new HashMap();
            addMap.put("is_custome_add", "1");
            List<HkFormIndex> listadd = hkFormIndexMapper.selectByMap(addMap);
            if (listadd.size() > 0) {
                FormAndItemResultVo vo = new FormAndItemResultVo();
                vo.setFormIndexId(listadd.get(0).getId());
               // vo.setFormIndexJson(listadd.get(0).getFormIndexJson());
                vo.setIndexName("自定义加分项");
                vo.setIndexScore((float)1);
                vo.setIndexId(PerformanceConstant.IS_CUSTOM_ADD);
                resultVo.add(vo);
            }
        }

        /*判断是否有自定义项，如果没有进行拼接*/

        if (!scoreIds.contains(PerformanceConstant.IS_CUSTOM_DELETE)) {
            Map deleteMap = new HashMap();
            deleteMap.put("is_custome_delete", "1");
            List<HkFormIndex> list = hkFormIndexMapper.selectByMap(deleteMap);
            if (list.size() > 0) {
                FormAndItemResultVo vo = new FormAndItemResultVo();
                vo.setFormIndexId(list.get(0).getId());
               // vo.setFormIndexJson(list.get(0).getFormIndexJson());
                vo.setIndexId(PerformanceConstant.IS_CUSTOM_DELETE);
                vo.setIndexScore((float)-1);
                vo.setIndexName("自定义减分项");
                resultVo.add(vo);
            }
        }
        resultVo.addAll(scoreVo);
        resultVo.addAll(deleteVo);
        resultVo.addAll(addVo);
        return resultVo;
    }

    @Override
    public EntityByFlowInstanceIdDataVo getFormEntityByFlowInstanceId(String flowInstanceId) {
        /*
         * 根据流程实例id获取所有当前得分
         * */
        QueryWrapper<HkAssessmentInfo> queryInfo = Wrappers.query();
        queryInfo.eq(HkAssessmentInfo.PROCESS_INSTANCE_ID,flowInstanceId);
        HkAssessmentInfo hkAssessmentInfos = hkAssessmentInfoMapper.selectOne(queryInfo);
        String fromId = hkAssessmentInfos.getFormKey();
        Integer isEnableOpinion = flowTaskInstanceService.getIsEnableOpinion(flowInstanceId);
        QueryWrapper<HkAssessmentScore> query = Wrappers.query();
        query.eq(HkAssessmentScore.PROCESS_INSTANCE_ID, flowInstanceId);
        query.eq(HkAssessmentScore.IS_CURRENT_ASSESSMENT, "1");
        List<HkAssessmentScore> hkAssessmentScores = hkAssessmentScoreMapper.selectList(query);
        QueryWrapper<HkFormRelationShip> query1 = Wrappers.query();
        QueryWrapper<HkFormRelationShip> eq = query1.eq(HkFormRelationShip.FORM_ID, fromId);
        eq.orderByAsc(HkFormRelationShip.SORT_NUMBER);
        List<HkFormRelationShip> hkFormRelationShips = hkFormRelationShipMapper.selectList(eq);
        List<String> items = new ArrayList<String>();
        Map<String, String> realtionMap = new HashMap<>();
        for (int i = 0; i < hkFormRelationShips.size(); i++) {
            HkFormRelationShip hkFormRelationShip = hkFormRelationShips.get(i);
            items.add(hkFormRelationShip.getItemId());
            realtionMap.put(hkFormRelationShip.getItemId(), hkFormRelationShip.getFormId());
        }
        List<IndexAndFormIdVo> resultVo = new ArrayList<IndexAndFormIdVo>();
        List<IndexAndFormIdVo> scoreVo = new ArrayList<IndexAndFormIdVo>();
        /*
         * 将表单分项和加分项进行重新排序并按加减分分组
         * 将该表单所有表单项关联查询
         *
         * */
        FormItemSortVo vo1=new FormItemSortVo();
        vo1.setFormId(fromId);
        vo1.setList(items);
        List<IndexAndFormIdVo> formAndItemResultVos = hkFormRelationShipMapper.selectFormAndItemResultVoByIndexIdsAndFormId(vo1);
        List<String> scoreIds = new ArrayList<String>();
        hkAssessmentScores.stream().forEach(hkAssessmentScore -> {
            IndexAndFormIdVo vo = new IndexAndFormIdVo();
            scoreIds.add(hkAssessmentScore.getIndexId());
            vo.setIndexName(hkAssessmentScore.getIndexName());
            vo.setFormIndexId(realtionMap.get(hkAssessmentScore.getIndexId()));
            vo.setScore(hkAssessmentScore.getScore());
            vo.setIndexDescribe(hkAssessmentScore.getIndexDescribe());
            vo.setProcessInstanceId(hkAssessmentScore.getProcessInstanceId());
            vo.setIndexId(hkAssessmentScore.getIndexId());
            vo.setScoreType(hkAssessmentScore.getScoreType());
            //vo.setIndexType(hkAssessmentScore.geti);
            //TODO 给vo添加图片
            List<String> igms=selectImgs(hkAssessmentScore);
            vo.setImglist(igms);
            vo.setIndexFrequency(hkAssessmentScore.getIndexFrequency());
            /*
             * 根据考核指标查找表单项
             * */
            if(hkAssessmentScore.getIndexComment()!=null){
                vo.setIndexComment(hkAssessmentScore.getIndexComment());
            }else{
                //当前的评论为空，查找之前的评论
            }
            scoreVo.add(vo);

        });
        /*
         * 将表单所有表单项查询出并排序
         * */

        for (int i = 0; i < formAndItemResultVos.size(); i++) {
            if (scoreIds.contains(formAndItemResultVos.get(i).getIndexId())) {
                 /*
                 yck 2021 当为打分项时将indexScore 装入之前的model中
                 * 当
                 * */
                for(int j=0;j<scoreVo.size();j++){
                    if(formAndItemResultVos.get(i).getIndexId().equals(scoreVo.get(j).getIndexId())){
                        scoreVo.get(j).setIndexScore(formAndItemResultVos.get(i).getIndexScore());
                        scoreVo.get(j).setIndexType(formAndItemResultVos.get(i).getIndexType());
                        scoreVo.get(j).setSortNumber(formAndItemResultVos.get(i).getSortNumber());
                        scoreVo.get(j).setModelName(formAndItemResultVos.get(i).getModelName());
                    }
                }
            }else {
                scoreVo.add(formAndItemResultVos.get(i));
            }
        }
        resultVo.addAll(scoreVo);
        EntityByFlowInstanceIdDataVo entityByFlowInstanceIdDataVo = new EntityByFlowInstanceIdDataVo();
        /*if (isEnableOpinion == null){

        }*/
        entityByFlowInstanceIdDataVo.setCommentType(isEnableOpinion);
        entityByFlowInstanceIdDataVo.setList(resultVo);
        return entityByFlowInstanceIdDataVo;
    }

    @Override
    public EntityByFlowInstanceIdDataVo selectFormEntityByflowIdAndPostId(String postId,String flowId,String templateVersion) {
        EntityByFlowInstanceIdDataVo entityByFlowInstanceIdDataVo = new EntityByFlowInstanceIdDataVo();
        Integer isEnableOpinion = flowTaskInstanceService.getInitIsEnableOpinion(flowId,templateVersion);
        entityByFlowInstanceIdDataVo.setCommentType(isEnableOpinion);
        List<IndexAndFormIdVo> vo = hkFormEntityMapper.selectFormEntityByFlowIdAndPostId(postId);
        if (vo.size() > 0){
            vo.stream().forEach(hkAssessmentScore -> {
                if (hkAssessmentScore.getIndexType() == 2){
                    hkAssessmentScore.setScoreType(HkAssessmentIndex.SCORE_TYPE_DELETE);
                }
            });
            entityByFlowInstanceIdDataVo.setList(vo);
        }else {
            new ArrayList<IndexAndFormIdVo>();
        }

        entityByFlowInstanceIdDataVo.setList(vo);
        return entityByFlowInstanceIdDataVo;
    }

    private String fromIndexJsonToString(String indexJsonStr){
        Map<String,Object> map=new HashMap<>(4);
        List<FormIndexJsonVo> indexJson=null;
        String json="";
        Map<String,Object> formindex = JSONObject.parseObject(indexJsonStr);
        if(!formindex.isEmpty()){
            List<Map<String,Object>> froms= (List<Map<String, Object>>) formindex.get("forms");
            indexJson=froms.stream().map(t-> BeanConvertUtils.mapToObject(t,FormIndexJsonVo.class)).collect(Collectors.toList());
            map.put("forms",indexJson);
            json = JSON.toJSONString(map);
        }
        return json;
    }
    private List<String> selectImgs(HkAssessmentScore hkAssessmentScore){
        QueryWrapper<HkAssessmentPicture> query=Wrappers.query();
        QueryWrapper<HkAssessmentPicture> eq = query.eq(HkAssessmentPicture.PROCESS_INSTANCE_ID, hkAssessmentScore.getProcessInstanceId())
                .eq(HkAssessmentPicture.INDEX_ID,hkAssessmentScore.getIndexId());
        List<HkAssessmentPicture> hkAssessmentPictures = hkAssessmentPictureMapper.selectList(eq);
        List<String> imgList=hkAssessmentPictures.stream().map(HkAssessmentPicture::getPictureUrl).collect(Collectors.toList());
        return imgList;
    }
    /*
     * 根据用户id查询
     * */
    @Override
    public List<FormAndItemResultVo> getFormEntityByUserId(String userId) throws Exception {

        HkFormEntity hkFormEntity = hkFormEntityMapper.selectFormEntityByUserId(userId);
//        if (hkFormEntity == null) {
//            throw new Exception("该用户还未绑定岗位或表单，请设置后再操作！");
//        }
        QueryWrapper<HkFormRelationShip> query = Wrappers.query();
        QueryWrapper<HkFormRelationShip> eq = query.eq(HkFormRelationShip.FORM_ID, hkFormEntity.getId());
        eq.orderByAsc(HkFormRelationShip.SORT_NUMBER);
        List<HkFormRelationShip> hkFormRelationShips = hkFormRelationShipMapper.selectList(eq);
        List<String> items = new ArrayList<String>();
        for (int i = 0; i < hkFormRelationShips.size(); i++) {
            HkFormRelationShip hkFormRelationShip = hkFormRelationShips.get(i);
            items.add(hkFormRelationShip.getItemId());
        }
        List<FormAndItemResultVo> resultVo = new ArrayList<FormAndItemResultVo>();
        List<FormAndItemResultVo> deleteVo = new ArrayList<FormAndItemResultVo>();
        List<FormAndItemResultVo> addVo = new ArrayList<FormAndItemResultVo>();
        /*
         * 将表单分项和加分项进行重新排序并按加减分分组
         * 将该表单所有表单项关联查询
         *
         * */
        FormItemSortVo vo3=new FormItemSortVo();
        vo3.setFormId(hkFormEntity.getId());
        vo3.setList(items);
        List<FormAndItemResultVo> formAndItemResultVos = hkFormRelationShipMapper.selectFormAndItemResultVoByFormItemIds(vo3);
        for (int i = 0; i < formAndItemResultVos.size(); i++) {
            /*String json=fromIndexJsonToString(formAndItemResultVos.get(i).getFormIndexJson());
            formAndItemResultVos.get(i).setFormIndexJson(json);*/
            if (formAndItemResultVos.get(i).getIndexScore() > 0) {
                addVo.add(formAndItemResultVos.get(i));
            } else {
                deleteVo.add(formAndItemResultVos.get(i));
            }
        }
//        Map addMap = new HashMap();
//        addMap.put("is_custome_add", "1");
//        List<HkFormIndex> listadd = hkFormIndexMapper.selectByMap(addMap);
//        if (listadd.size() > 0) {
//            String json=fromIndexJsonToString(listadd.get(0).getFormIndexJson());
//            FormAndItemResultVo vo = new FormAndItemResultVo();
//            vo.setFormIndexId(listadd.get(0).getId());
//            vo.setFormIndexJson(json);
//            vo.setIndexName("自定义加分项");
//            vo.setIndexId(PerformanceConstant.IS_CUSTOM_ADD);
//            resultVo.add(vo);
//        }
//        /*
//         * 查询减分自定义项
//         * */
//        Map deleteMap = new HashMap();
//        deleteMap.put("is_custome_delete", "1");
//        List<HkFormIndex> list = hkFormIndexMapper.selectByMap(deleteMap);
//        if (list.size() > 0) {
//            String json=fromIndexJsonToString(list.get(0).getFormIndexJson());
//            FormAndItemResultVo vo = new FormAndItemResultVo();
//            vo.setFormIndexId(list.get(0).getId());
//            vo.setFormIndexJson(json);
//            vo.setIndexId(PerformanceConstant.IS_CUSTOM_DELETE);
//            vo.setIndexName("自定义减分项");
//            resultVo.add(vo);
//        }

        resultVo.addAll(deleteVo);
        resultVo.addAll(addVo);
        return resultVo;
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<HkFormEntity> getEntityWrapper(QueryWrapper<HkFormEntity> entityWrapper, HkFormEntity hkFormEntity) {
        //条件拼接
        if (StringUtils.isNotBlank(hkFormEntity.getCreateBy())) {
            entityWrapper.like(HkFormEntity.CREATE_BY, hkFormEntity.getCreateBy());
        }
               /* if(StringUtils.isNotBlank(hkFormEntity.getCreateTime())){
                entityWrapper.like(HkFormEntity.CREATE_TIME,hkFormEntity.getCreateTime());
                }
                if(StringUtils.isNotBlank(hkFormEntity.getDelFlag())){
                entityWrapper.like(HkFormEntity.DEL_FLAG,hkFormEntity.getDelFlag());
                }
                if(StringUtils.isNotBlank(hkFormEntity.getUpdateBy())){
                entityWrapper.like(HkFormEntity.UPDATE_BY,hkFormEntity.getUpdateBy());
                }
                if(StringUtils.isNotBlank(hkFormEntity.getUpdateTime())){
                entityWrapper.like(HkFormEntity.UPDATE_TIME,hkFormEntity.getUpdateTime());
                }*/
        /*if (StringUtils.isNotBlank(hkFormEntity.getFormItemIds())) {
            entityWrapper.like(HkFormEntity.FORM_ITEM_IDS, hkFormEntity.getFormItemIds());
        }
        if (StringUtils.isNotBlank(hkFormEntity.getFormJson())) {
            entityWrapper.like(HkFormEntity.FORM_JSON, hkFormEntity.getFormJson());
        }*/
        if (StringUtils.isNotBlank(hkFormEntity.getFormName())) {
            entityWrapper.like(HkFormEntity.FORM_NAME, hkFormEntity.getFormName());
        }
        return entityWrapper;
    }
}